package com.hdax.dmw.user.service.impl;

import com.hdax.dmw.common.exceptions.MsgException;
import com.hdax.dmw.common.utils.Result;
import com.hdax.dmw.common.utils.ResultGenerator;
import com.hdax.dmw.common.utils.ServiceResultEnum;
import com.hdax.dmw.user.dtos.LoginDto;
import com.hdax.dmw.user.service.MsgLoginService;
import com.hdax.dmw.user.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static com.hdax.dmw.common.utils.ServiceResultEnum.*;

@Service
public class MsgLoginServiceImpl implements MsgLoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Result<String> sendMsg(String phoneNumber) {
        if(redisTemplate.hasKey("vcode:"+phoneNumber)){
           throw new MsgException(ServiceResultEnum.LOGIN_VERIFY_CODE_REPEAT);
        }
        Random random = new Random();
        //[1000,9999]
        String vcode = random.nextInt(1000,10000)+"";
        Map<String,String> params = new HashMap<>();
        params.put("phoneNumber",phoneNumber);
        params.put("vcode",vcode);
        redisTemplate.opsForValue().set("vcode:"+phoneNumber,vcode+"", Duration.ofMinutes(1L));
        rabbitTemplate.convertAndSend("dmsms",vcode+"");
        return ResultGenerator.genSuccessResult(vcode+"");
    }

    @Autowired
    private UserService userService;

    @Override
    public Result<LoginDto> login(String phoneNumber, String vcode) {
        if(vcode==null || vcode.trim().equals("")){
            throw new MsgException(LOGIN_VERIFY_CODE_NULL);
        }
        //缓存中的验证码和输入的验证码比较
        if(!redisTemplate.hasKey("vcode:"+phoneNumber)){
            throw new MsgException(LOGIN_VERIFY_CODE_EXPIRE);
        }
        String realCode = (String) redisTemplate.opsForValue().get("vcode:" + phoneNumber);
        if(!realCode.equals(vcode)){
            throw new MsgException(LOGIN_VERIFY_CODE_ERROR);
        }
        Result<LoginDto> login = userService.login(phoneNumber);
        return login;
    }
}
